package com.genexususa.eo.google.connection;

import com.genexususa.eo.google.data.*;
import com.google.api.ads.adwords.axis.v201406.cm.*;
import org.w3c.dom.Document;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.Marshaller;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathFactory;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.rmi.RemoteException;
import java.util.ArrayList;
import java.util.List;

public class FeedManager {

    private String _clientId;

    public void SetClientId(String clientId) {
        this._clientId = clientId;
    }

    public String GetClientId() {
        return _clientId;
    }

    public void Finalize() {

        SessionController sc = SessionController.getInstance();
        sc.RemoveSession(_clientId);
    }

    private static final int PAGE_SIZE = 100;

    private static final int PLACEHOLDER_SITELINKS = 1;
    private static final int PLACEHOLDER_CALL = 2;
    private static final int PLACEHOLDER_APP = 3;


    // See the Placeholder reference page for a list of all the placeholder types and fields.
    // https://developers.google.com/adwords/api/docs/appendix/placeholders
    private static final int PLACEHOLDER_FIELD_SITELINK_LINK_TEXT = 1;
    private static final int PLACEHOLDER_FIELD_SITELINK_URL = 2;


    public String CreateFeed(String xml){

        try{

            String result = "";

            //GA_ResultCreateCampaigns res = new GA_ResultCreateCampaigns();

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_Feed");

            Object feedNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList feeds = (NodeList) feedNodes;

            ArrayList<GA_ResultItem> feedItems = new ArrayList<GA_ResultItem>();

            if (feeds.getLength() > 0) {

                for (int i = 0; i < feeds.getLength(); i++) { // For all GA_Feed Nodes

                    Node n = feeds.item(i);

                    NodeList children = n.getChildNodes();

                    GA_ResultItem resultItem = new GA_ResultItem();

                    if (children.getLength() > 0) {

                        //FeedAttribute[] attributes = new FeedAttribute[]{};

                        int feedType = 0;

                        for (int j = 0; j < children.getLength(); j++) {

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedTypeId")) {
                                feedType = Integer.parseInt(children.item(j).getTextContent());
                                break;
                            }

                        }


                        ArrayList<FeedAttribute> attributes = new ArrayList<FeedAttribute>();

                        Feed feed = new Feed();

                        feed.setOrigin(FeedOrigin.USER);

                        for (int j = 0; j < children.getLength(); j++) {


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedName")) {
                                feed.setName(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedGxId")) {
                                resultItem.FeedGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedTypeId")) {
                                resultItem.FeedTypeId = Integer.parseInt(children.item(j).getTextContent());
                            }



                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedAttributes")){

                                NodeList attChildren = children.item(j).getChildNodes();


                                for (int index = 0; index < attChildren.getLength(); index++){


                                    if  (attChildren.item(index).getNodeName().equalsIgnoreCase("FeedAttribute")){

                                        NodeList feedAttChildren = attChildren.item(index).getChildNodes();
                                        FeedAttribute att = new FeedAttribute();

                                        GA_FeedAttribute feedAttribute = new GA_FeedAttribute();
                                        for (int h = 0; h < feedAttChildren.getLength(); h++){

                                            if (feedAttChildren.item(h).getNodeName().equalsIgnoreCase("FeedAttName")){
                                                att.setName(feedAttChildren.item(h).getTextContent());
                                                feedAttribute.FeedAttrName = feedAttChildren.item(h).getTextContent();
                                            }

                                            if (feedAttChildren.item(h).getNodeName().equalsIgnoreCase("FeedAttGxId")){
                                                feedAttribute.FeedAttrGxId = Long.parseLong(feedAttChildren.item(h).getTextContent());
                                            }

                                            if (feedAttChildren.item(h).getNodeName().equalsIgnoreCase("FeedAttDataType")){

                                                String attType = feedAttChildren.item(h).getTextContent();

                                                if (attType.equalsIgnoreCase("INT64")){
                                                    att.setType(FeedAttributeType.INT64);
                                                }else if (attType.equalsIgnoreCase("FLOAT")){
                                                    att.setType(FeedAttributeType.FLOAT);
                                                }else if (attType.equalsIgnoreCase("STRING")){
                                                    att.setType(FeedAttributeType.STRING);
                                                }else if (attType.equalsIgnoreCase("BOOLEAN")){
                                                    att.setType(FeedAttributeType.BOOLEAN);
                                                }else if (attType.equalsIgnoreCase("URL")){
                                                    att.setType(FeedAttributeType.URL);
                                                }else if (attType.equalsIgnoreCase("DATE_TIME")){
                                                    att.setType(FeedAttributeType.DATE_TIME);
                                                }else{
                                                    att.setType(FeedAttributeType.UNKNOWN);
                                                }

                                            }

                                            if (feedAttChildren.item(h).getNodeName().equalsIgnoreCase("FeedAttTypeId")){
                                                feedAttribute.FeedAttTypeId = Integer.parseInt(feedAttChildren.item(h).getTextContent());
                                            }
                                        }



                                    attributes.add(att);
                                    feedAttribute.FeedAttribute = att;
                                    resultItem.FeedAttributes.add(feedAttribute);
                                }

                                }
                            }
                        }

                        FeedAttribute[] feedAtts = new FeedAttribute[]{};

                        FeedAttribute[] feedAttributes = attributes.toArray(feedAtts);

                        feed.setAttributes(feedAttributes);

                        resultItem.Feed = feed;


                        feedItems.add(resultItem);


                    }

                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<FeedOperation> ops = new ArrayList<FeedOperation>();

                for (GA_ResultItem feedItem : feedItems){

                    FeedOperation operation = new FeedOperation();
                    operation.setOperand(feedItem.Feed);
                    operation.setOperator(Operator.ADD);

                    ops.add(operation);
                }

                FeedOperation[] opsArray = new FeedOperation[]{};

                FeedOperation[] operations = ops.toArray(opsArray);


                FeedServiceInterface feedService = sf.GetFeedServiceInterface(this._clientId);

                FeedReturnValue returnValue = feedService.mutate(operations);
                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createdFeed = new GA_ResultItem();

                    createdFeed.FeedGxId = feedItems.get(i).FeedGxId;
                    createdFeed.FeedAttributes = feedItems.get(i).FeedAttributes;


                    if (returnValue.getValue(i) == null){




                    }else {

                        createdFeed.FeedId = returnValue.getValue(i).getId();
                        createdFeed.FeedTypeId = feedItems.get(i).FeedTypeId;

                        for (int index = 0; index < returnValue.getValue(i).getAttributes().length; index++){

                            createdFeed.FeedAttributes.get(index).FeedAttrId = returnValue.getValue(i).getAttributes()[index].getId();

                        }

                        created.add(createdFeed);


                    }




                }

                FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(this._clientId);

                for (GA_ResultItem createdItem : created){

                    FeedMapping feedMapping = new FeedMapping();

                    feedMapping.setFeedId(createdItem.FeedId);
                    feedMapping.setPlaceholderType(createdItem.FeedTypeId);

                    ArrayList<AttributeFieldMapping> attFieldMappings = new ArrayList<AttributeFieldMapping>();

                    for (int i = 0; i < createdItem.FeedAttributes.size(); i++) {

                        AttributeFieldMapping fieldMapping = new AttributeFieldMapping();
                        GA_FeedAttribute feedAttribute = createdItem.FeedAttributes.get(i);

                        fieldMapping.setFeedAttributeId(feedAttribute.FeedAttrId);
                        fieldMapping.setFieldId(feedAttribute.FeedAttTypeId);

                        attFieldMappings.add(fieldMapping);


                    }


                    AttributeFieldMapping[] arrayFieldMapping = new AttributeFieldMapping[]{};

                    feedMapping.setAttributeFieldMappings(attFieldMappings.toArray(arrayFieldMapping));

                    FeedMappingOperation operation = new FeedMappingOperation();
                    operation.setOperand(feedMapping);
                    operation.setOperator(Operator.ADD);

                    FeedMappingReturnValue resultFeedMapping =
                            feedMappingService.mutate(new FeedMappingOperation[] {operation});

                    createdItem.FeedMapping = feedMapping;
                    createdItem.FeedMappingId = resultFeedMapping.getValue()[0].getFeedMappingId();



                }



                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }


            }

            return result;

        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public String DeleteFeed(String xml){
        try{
            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_Feed");

            Object feedNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList feeds = (NodeList) feedNodes;

            ArrayList<GA_ResultItem> feedItems = new ArrayList<GA_ResultItem>();
            if (feeds.getLength() > 0) {

                for (int i = 0; i < feeds.getLength(); i++) { // For all GA_Feed Nodes

                    Node n = feeds.item(i);

                    NodeList children = n.getChildNodes();

                    GA_ResultItem resultItem = new GA_ResultItem();

                    if (children.getLength() > 0) {


                        ArrayList<FeedAttribute> attributes = new ArrayList<FeedAttribute>();

                        Feed feed = new Feed();

                        feed.setOrigin(FeedOrigin.USER);

                        for (int j = 0; j < children.getLength(); j++) {


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedName")) {
                                feed.setName(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedGxId")) {
                                resultItem.FeedGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedTypeId")) {
                                resultItem.FeedTypeId = Integer.parseInt(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedId")) {
                                resultItem.FeedId = Long.parseLong(children.item(j).getTextContent());
                                feed.setId(Long.parseLong(children.item(j).getTextContent()));
                            }




                        }

                        resultItem.Feed = feed;


                        feedItems.add(resultItem);


                    }

                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<FeedOperation> ops = new ArrayList<FeedOperation>();

                for (GA_ResultItem feedItem : feedItems){

                    FeedOperation operation = new FeedOperation();
                    operation.setOperand(feedItem.Feed);
                    operation.setOperator(Operator.REMOVE);

                    ops.add(operation);
                }

                FeedOperation[] opsArray = new FeedOperation[]{};

                FeedOperation[] operations = ops.toArray(opsArray);


                FeedServiceInterface feedService = sf.GetFeedServiceInterface(this._clientId);

                FeedReturnValue returnValue = feedService.mutate(operations);
                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createdFeed = new GA_ResultItem();

                    createdFeed.FeedGxId = feedItems.get(i).FeedGxId;
                    createdFeed.FeedAttributes = feedItems.get(i).FeedAttributes;
                    createdFeed.AdExtensionGxId = feedItems.get(i).AdExtensionGxId;
                    createdFeed.SubCampaignGxId = feedItems.get(i).SubCampaignGxId;



                    if (returnValue.getValue(i) == null){




                    }else {

                        createdFeed.FeedId = returnValue.getValue(i).getId();
                        createdFeed.FeedTypeId = feedItems.get(i).FeedTypeId;



                        created.add(createdFeed);


                    }




                }




                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }


            }

            return result;


        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public String UpdateFeedItems(String xml){

        try{

            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                    = xpath.compile("//GA_FeedInstance");

            Object feedNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList feedInstances = (NodeList) feedNodes;

            ArrayList<GA_ResultItem> feedItems = new ArrayList<GA_ResultItem>();

            if (feedInstances.getLength() > 0){


                for (int i = 0; i < feedInstances.getLength(); i++) { // For all GA_FeedInstance Nodes

                    Node n = feedInstances.item(i);

                    NodeList children = n.getChildNodes();

                    GA_ResultItem resultItem = new GA_ResultItem();

                    if (children.getLength() > 0) {

                        ArrayList<FeedItemOperation > itemOperations = new ArrayList<FeedItemOperation>();

                        Long feedId = 0L;

                        FeedItem feedItem = new FeedItem();

                        for (int j = 0; j < children.getLength(); j++) {

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedId")) {
                                feedId = Long.parseLong(children.item(j).getTextContent());
                                feedItem.setFeedId(feedId);
                                resultItem.FeedId = feedId;
                                break;
                            }
                        }

                        //FeedItem fi = new FeedItem();

                        for (int j = 0; j < children.getLength(); j++){


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedItemId")) {
                                feedItem.setFeedItemId(Long.parseLong(children.item(j).getTextContent()));
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedGxId")) {
                                resultItem.FeedGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedTypeId")) {
                                resultItem.FeedTypeId = Integer.parseInt(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedId")) {
                                resultItem.FeedId = Long.parseLong(children.item(j).getTextContent());
                                feedItem.setFeedId(Long.parseLong(children.item(j).getTextContent()));
                            }



                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                resultItem.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("AdExtensionGxId")) {
                                resultItem.AdExtensionGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedAttributes")) {

                                NodeList attChildren = children.item(j).getChildNodes();

                                FeedItemOperation operation = new FeedItemOperation();

                                ArrayList<FeedItemAttributeValue> attValues = new ArrayList<FeedItemAttributeValue>();

                                for (int h = 0; h < attChildren.getLength(); h++){

                                    if (attChildren.item(h).getNodeName().equalsIgnoreCase("FeedAttribute")){

                                        NodeList child = attChildren.item(h).getChildNodes();

                                        FeedItemAttributeValue attValue = new FeedItemAttributeValue();

                                        String attType = "";

                                        GA_FeedAttribute feedAttribute = new GA_FeedAttribute();

                                        for (int index = 0; index < child.getLength(); index++){

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeDataType")){
                                                attType = child.item(index).getTextContent();
                                                break;
                                            }
                                        }


                                        for (int index = 0; index < child.getLength(); index++){

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeId")){
                                                attValue.setFeedAttributeId(Long.parseLong(child.item(index).getTextContent()));
                                                feedAttribute.FeedAttrId = Long.parseLong(child.item(index).getTextContent());
                                            }

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeGxId")){
                                                feedAttribute.FeedAttrGxId = Long.parseLong(child.item(index).getTextContent());
                                            }

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeTypeId")){
                                                feedAttribute.FeedAttTypeId = Integer.parseInt(child.item(index).getTextContent());
                                            }

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeValue")){

                                                if (attType.equalsIgnoreCase("INT64")){
                                                    attValue.setIntegerValue(Long.parseLong(child.item(index).getTextContent()));
                                                }else if (attType.equalsIgnoreCase("FLOAT")){
                                                    attValue.setDoubleValue(Double.parseDouble(child.item(index).getTextContent()));
                                                }else if (attType.equalsIgnoreCase("STRING")){
                                                    attValue.setStringValue(child.item(index).getTextContent());
                                                }else if (attType.equalsIgnoreCase("BOOLEAN")){
                                                    attValue.setBooleanValue(Boolean.parseBoolean(child.item(index).getTextContent()));
                                                }else if (attType.equalsIgnoreCase("URL")){
                                                    attValue.setStringValue(child.item(index).getTextContent());
                                                }else if (attType.equalsIgnoreCase("DATE_TIME")){
                                                    attValue.setStringValue(child.item(index).getTextContent());
                                                }/*else{
                                                    att.setType(FeedAttributeType.UNKNOWN);
                                                }*/


                                            }

                                        }

                                        attValues.add(attValue);

                                        resultItem.FeedAttributes.add(feedAttribute);

                                    }


                                }

                                FeedItemAttributeValue[] attributeValues = new FeedItemAttributeValue[]{};

                                feedItem.setAttributeValues(attValues.toArray(attributeValues));

                                operation = new FeedItemOperation();
                                operation.setOperand(feedItem);
                                operation.setOperator(Operator.SET);

                                itemOperations.add(operation);



                            }
                        }


                        FeedItemOperation[] operationsArray = new FeedItemOperation[] {};

                        FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);


                        FeedItemReturnValue returnValue = feedItemService.mutate(itemOperations.toArray(operationsArray));
                        Thread.sleep(1000);


                        //returnValue.getValue()



                        int j = 0;


                        for (int ind = 0; ind < returnValue.getValue().length; ind++) {


                            if (returnValue.getPartialFailureErrors()!= null){
                                resultItem.HasError = true;
                                ErrorsStruct errors = new ErrorsStruct();

                                errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                                errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                                com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                                err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                                err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                                //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                                err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                                err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();



                                j++;
                                errors.Errors.add(err);

                                resultItem.Errors = errors;


                            }else{


                                resultItem.FeedItemId = returnValue.getValue()[ind].getFeedItemId();
                            }



                        }




                        feedItems.add(resultItem);


                    }


                    try {

                        JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                        Marshaller marshallerObj = contextObj.createMarshaller();
                        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                        StringWriter sw = new StringWriter();

                        res.Items = feedItems;

                        marshallerObj.marshal(res, sw);
                        result = sw.getBuffer().toString();
                        System.out.println(result);
                        String s = "";

                    } catch (Exception exc) {
                        exc.printStackTrace();
                        result = exc.getMessage();
                    }
                }
            }

            return result;

        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }

    public String DeleteFeedItems(String xml){
        try{
            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr = xpath.compile("//GA_FeedInstance");

            Object feedNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList feeds = (NodeList) feedNodes;

            ArrayList<GA_ResultItem> feedItems = new ArrayList<GA_ResultItem>();

            ArrayList<FeedItem> feedItemsList = new ArrayList<FeedItem>();
            if (feeds.getLength() > 0) {

                for (int i = 0; i < feeds.getLength(); i++) { // For all GA_FeedItem Nodes

                    Node n = feeds.item(i);

                    NodeList children = n.getChildNodes();

                    GA_ResultItem resultItem = new GA_ResultItem();

                    if (children.getLength() > 0) {

                        FeedItem feedItem = new FeedItem();


                        for (int j = 0; j < children.getLength(); j++) {


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedId")) {
                                feedItem.setFeedId(Long.parseLong(children.item(j).getTextContent()));
                                resultItem.FeedId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                resultItem.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdExtensionGxId")) {
                                resultItem.AdExtensionGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedGxId")) {
                                resultItem.FeedGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedItemId")) {
                                feedItem.setFeedItemId(Long.parseLong(children.item(j).getTextContent()));
                            }
                        }

                        //resultItem.Feed = feed;

                        feedItemsList.add(feedItem);
                        feedItems.add(resultItem);


                    }

                }

                ArrayList<GA_ResultItem> created = new ArrayList<GA_ResultItem>();

                ArrayList<FeedItemOperation> ops = new ArrayList<FeedItemOperation>();

                for (FeedItem feedItem : feedItemsList){

                    FeedItemOperation operation = new FeedItemOperation();
                    operation.setOperand(feedItem);
                    operation.setOperator(Operator.REMOVE);

                    ops.add(operation);
                }

                FeedItemOperation[] opsArray = new FeedItemOperation[]{};

                FeedItemOperation[] operations = ops.toArray(opsArray);


                FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);

                FeedItemReturnValue returnValue = feedItemService.mutate(operations);
                Thread.sleep(1000);

                int j = 0;

                for (int i = 0; i < returnValue.getValue().length; i++) {

                    GA_ResultItem createdFeed = new GA_ResultItem();

                    createdFeed.FeedGxId = feedItems.get(i).FeedGxId;
                    createdFeed.AdExtensionGxId = feedItems.get(i).AdExtensionGxId;
                    createdFeed.SubCampaignGxId = feedItems.get(i).SubCampaignGxId;

                    int h = 0;
                    if (returnValue.getPartialFailureErrors()!= null){
                        createdFeed.HasError = true;
                        ErrorsStruct errors = new ErrorsStruct();

                        errors.Message = returnValue.getPartialFailureErrors(h).getErrorString();

                        errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                        com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                        err.ErrorString = returnValue.getPartialFailureErrors(h).getErrorString();
                        err.fieldPath = returnValue.getPartialFailureErrors(h).getFieldPath();
                        //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                        err.Trigger = returnValue.getPartialFailureErrors(h).getTrigger();
                        err.Type = returnValue.getPartialFailureErrors(h).getApiErrorType();



                        h++;
                        errors.Errors.add(err);

                        createdFeed.Errors = errors;


                    }else{

                        createdFeed.FeedTypeId = feedItems.get(i).FeedTypeId;





                        //resultItem.FeedItemId = returnValue.getValue()[ind].getFeedItemId();
                    }
                    //createdFeed.FeedItemGxId = feedItems.get(i).FeedItemGxId;

                    //createdFeed.FeedItems.get(i).
                    //createdFeed.FeedAttributes = feedItems.get(i).FeedAttributes;


                    created.add(createdFeed);




                }




                try {

                    JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                    Marshaller marshallerObj = contextObj.createMarshaller();
                    marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                    StringWriter sw = new StringWriter();

                    res.Items = created;

                    marshallerObj.marshal(res, sw);
                    result = sw.getBuffer().toString();
                    System.out.println(result);
                    String s = "";

                } catch (Exception exc) {
                    exc.printStackTrace();
                    result = exc.getMessage();
                }


            }

            return result;


        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }

    }


    public String AddFeedInstance(String xml){

        try{

            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            Util util = new Util();

            Document doc = util.loadXMLFromString(xml);

            XPathFactory factory = XPathFactory.newInstance();
            XPath xpath = factory.newXPath();

            XPathExpression expr
                        = xpath.compile("//GA_FeedInstance");

            Object feedNodes = expr.evaluate(doc, XPathConstants.NODESET);

            NodeList feedInstances = (NodeList) feedNodes;

            ArrayList<GA_ResultItem> feedItems = new ArrayList<GA_ResultItem>();

            if (feedInstances.getLength() > 0){


                for (int i = 0; i < feedInstances.getLength(); i++) { // For all GA_FeedInstance Nodes

                    Node n = feedInstances.item(i);

                    NodeList children = n.getChildNodes();

                    GA_ResultItem resultItem = new GA_ResultItem();

                    if (children.getLength() > 0) {

                        ArrayList<FeedItemOperation > itemOperations = new ArrayList<FeedItemOperation>();

                        Long feedId = 0L;

                        FeedItem feedItem = new FeedItem();

                        for (int j = 0; j < children.getLength(); j++) {

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedId")) {
                                feedId = Long.parseLong(children.item(j).getTextContent());
                                feedItem.setFeedId(feedId);
                                resultItem.FeedId = feedId;
                                break;
                            }
                        }


                        for (int j = 0; j < children.getLength(); j++){


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedGxId")) {
                                resultItem.FeedGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("SubCampaignGxId")) {
                                resultItem.SubCampaignGxId = Long.parseLong(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedTypeId")) {
                                resultItem.FeedTypeId = Integer.parseInt(children.item(j).getTextContent());
                            }

                            if (children.item(j).getNodeName().equalsIgnoreCase("AdExtensionGxId")) {
                                resultItem.AdExtensionGxId = Long.parseLong(children.item(j).getTextContent());
                            }


                            if (children.item(j).getNodeName().equalsIgnoreCase("FeedAttributes")) {

                                NodeList attChildren = children.item(j).getChildNodes();

                                FeedItemOperation operation = new FeedItemOperation();

                                ArrayList<FeedItemAttributeValue> attValues = new ArrayList<FeedItemAttributeValue>();

                                for (int h = 0; h < attChildren.getLength(); h++){

                                    if (attChildren.item(h).getNodeName().equalsIgnoreCase("FeedAttribute")){

                                        NodeList child = attChildren.item(h).getChildNodes();

                                        FeedItemAttributeValue attValue = new FeedItemAttributeValue();

                                        String attType = "";

                                        GA_FeedAttribute feedAttribute = new GA_FeedAttribute();

                                        for (int index = 0; index < child.getLength(); index++){

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeDataType")){
                                                attType = child.item(index).getTextContent();
                                                break;
                                            }
                                        }


                                        for (int index = 0; index < child.getLength(); index++){

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeId")){
                                                attValue.setFeedAttributeId(Long.parseLong(child.item(index).getTextContent()));
                                                feedAttribute.FeedAttrId = Long.parseLong(child.item(index).getTextContent());
                                            }

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeGxId")){
                                                feedAttribute.FeedAttrGxId = Long.parseLong(child.item(index).getTextContent());
                                            }

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeTypeId")){
                                                feedAttribute.FeedAttTypeId = Integer.parseInt(child.item(index).getTextContent());
                                            }

                                            if (child.item(index).getNodeName().equalsIgnoreCase("FeedAttributeValue")){

                                                if (attType.equalsIgnoreCase("INT64")){
                                                    attValue.setIntegerValue(Long.parseLong(child.item(index).getTextContent()));
                                                }else if (attType.equalsIgnoreCase("FLOAT")){
                                                    attValue.setDoubleValue(Double.parseDouble(child.item(index).getTextContent()));
                                                }else if (attType.equalsIgnoreCase("STRING")){
                                                    attValue.setStringValue(child.item(index).getTextContent());
                                                }else if (attType.equalsIgnoreCase("BOOLEAN")){
                                                    attValue.setBooleanValue(Boolean.parseBoolean(child.item(index).getTextContent()));
                                                }else if (attType.equalsIgnoreCase("URL")){
                                                    attValue.setStringValue(child.item(index).getTextContent());
                                                }else if (attType.equalsIgnoreCase("DATE_TIME")){
                                                    attValue.setStringValue(child.item(index).getTextContent());
                                                }/*else{
                                                    att.setType(FeedAttributeType.UNKNOWN);
                                                }*/


                                            }

                                        }

                                        attValues.add(attValue);

                                        resultItem.FeedAttributes.add(feedAttribute);

                                    }


                                }

                                FeedItemAttributeValue[] attributeValues = new FeedItemAttributeValue[]{};

                                feedItem.setAttributeValues(attValues.toArray(attributeValues));

                                operation = new FeedItemOperation();
                                operation.setOperand(feedItem);
                                operation.setOperator(Operator.ADD);

                                itemOperations.add(operation);



                            }
                        }


                        FeedItemOperation[] operationsArray = new FeedItemOperation[] {};

                        FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);


                        FeedItemReturnValue returnValue = feedItemService.mutate(itemOperations.toArray(operationsArray));
                        Thread.sleep(1000);


                        //returnValue.getValue()



                        int j = 0;


                        for (int ind = 0; ind < returnValue.getValue().length; ind++) {


                            if (returnValue.getPartialFailureErrors()!= null){
                                resultItem.HasError = true;
                                ErrorsStruct errors = new ErrorsStruct();

                                errors.Message = returnValue.getPartialFailureErrors(j).getErrorString();

                                errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

                                com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

                                err.ErrorString = returnValue.getPartialFailureErrors(j).getErrorString();
                                err.fieldPath = returnValue.getPartialFailureErrors(j).getFieldPath();
                                //err.Reason = returnValue.getPartialFailureErrors(i). .getFaultReason();
                                err.Trigger = returnValue.getPartialFailureErrors(j).getTrigger();
                                err.Type = returnValue.getPartialFailureErrors(j).getApiErrorType();



                                j++;
                                errors.Errors.add(err);

                                resultItem.Errors = errors;


                            }else{


                                resultItem.FeedItemId = returnValue.getValue()[ind].getFeedItemId();
                            }



                        }




                        feedItems.add(resultItem);


                    }


                    try {

                        JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                        Marshaller marshallerObj = contextObj.createMarshaller();
                        marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                        StringWriter sw = new StringWriter();

                        res.Items = feedItems;

                        marshallerObj.marshal(res, sw);
                        result = sw.getBuffer().toString();
                        System.out.println(result);
                        String s = "";

                    } catch (Exception exc) {
                        exc.printStackTrace();
                        result = exc.getMessage();
                    }
                }
            }

            return result;

        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }
    }

    public String DisassociateFeedInstanceCampaign(Long feedId, String feedItemIds, Long campaignId, int feedTypeId){

        try{

            String result = "";

            //GA_ResultCreateCampaigns res = new GA_ResultCreateCampaigns();


            String[] itemIdArray = feedItemIds.split(";");

            ArrayList<Long> itemIds = new ArrayList<Long>();

            for (String itemId : itemIdArray){

                itemIds.add(Long.parseLong(itemId));

            }

            GA_Result res = new GA_Result();

            GA_ResultItem resultItem = new GA_ResultItem();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            CampaignFeedServiceInterface campaignFeedService = sf.GetCampaignFeedServiceInterface(this._clientId);

            RequestContextOperand requestContextOperand = new RequestContextOperand();
            requestContextOperand.setContextType(RequestContextOperandContextType.FEED_ITEM_ID);

            Function function = new Function();
            function.setLhsOperand(new FunctionArgumentOperand[] {requestContextOperand});
            function.setOperator(FunctionOperator.IN);

            List<FunctionArgumentOperand> operands = new ArrayList<FunctionArgumentOperand>();

            for (Long feedItemId : itemIds){
                ConstantOperand constantOperand = new ConstantOperand();
                constantOperand.setLongValue(feedItemId);
                constantOperand.setType(ConstantOperandConstantType.LONG);
                operands.add(constantOperand);
            }



            function.setRhsOperand(operands.toArray(new FunctionArgumentOperand[operands.size()]));
            CampaignFeed campaignFeed = new CampaignFeed();
            campaignFeed.setFeedId(feedId);
            campaignFeed.setCampaignId(campaignId);

            campaignFeed.setMatchingFunction(function);

            campaignFeed.setPlaceholderTypes(new int[] {feedTypeId});


            CampaignFeedOperation operation = new CampaignFeedOperation();
            operation.setOperand(campaignFeed);
            operation.setOperator(Operator.REMOVE);
            CampaignFeedReturnValue returnValue =
                    campaignFeedService.mutate(new CampaignFeedOperation[] {operation});

             /*for (CampaignFeed savedCampaignFeed : result.getValue()) {
                 System.out.printf("Campaign with ID %d was associated with feed with ID %d.\n",
                         savedCampaignFeed.getCampaignId(), savedCampaignFeed.getFeedId());
             }*/


            resultItem.FeedId = feedId;
            resultItem.CampaignId = campaignId;
            //resultItem.FeedItemId = feedItemId;
            resultItem.FeedTypeId = feedTypeId;
            resultItem.HasError = false;

            items.add(resultItem);



            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            }

            return result;






        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }



    }


    public String AssociateFeedInstanceCampaign(Long feedId, String feedItemIds, Long campaignId, int feedTypeId){

         try{

             String result = "";

             //GA_ResultCreateCampaigns res = new GA_ResultCreateCampaigns();

             GA_Result res = new GA_Result();

             GA_ResultItem resultItem = new GA_ResultItem();

             ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();


             String[] itemIdArray = feedItemIds.split(";");

             ArrayList<Long> itemIds = new ArrayList<Long>();

             for (String itemId : itemIdArray){

                 itemIds.add(Long.parseLong(itemId));

             }




             // Get the instance of service's factory
             ServiceFactory sf = ServiceFactory.getInstance();

             CampaignFeedServiceInterface campaignFeedService = sf.GetCampaignFeedServiceInterface(this._clientId);

             RequestContextOperand requestContextOperand = new RequestContextOperand();
             requestContextOperand.setContextType(RequestContextOperandContextType.FEED_ITEM_ID);

             Function function = new Function();
             function.setLhsOperand(new FunctionArgumentOperand[] {requestContextOperand});
             function.setOperator(FunctionOperator.IN);

             List<FunctionArgumentOperand> operands = new ArrayList<FunctionArgumentOperand>();

             for (Long feedItemId : itemIds){
                 ConstantOperand constantOperand = new ConstantOperand();
                 constantOperand.setLongValue(feedItemId);
                 constantOperand.setType(ConstantOperandConstantType.LONG);
                 operands.add(constantOperand);
             }

             function.setRhsOperand(operands.toArray(new FunctionArgumentOperand[operands.size()]));
             CampaignFeed campaignFeed = new CampaignFeed();
             campaignFeed.setFeedId(feedId);
             campaignFeed.setCampaignId(campaignId);

             campaignFeed.setMatchingFunction(function);

             campaignFeed.setPlaceholderTypes(new int[] {feedTypeId});

             CampaignFeedOperation operation = new CampaignFeedOperation();
             operation.setOperand(campaignFeed);
             operation.setOperator(Operator.ADD);
             CampaignFeedReturnValue returnValue =
                     campaignFeedService.mutate(new CampaignFeedOperation[] {operation});

             /*for (CampaignFeed savedCampaignFeed : result.getValue()) {
                 System.out.printf("Campaign with ID %d was associated with feed with ID %d.\n",
                         savedCampaignFeed.getCampaignId(), savedCampaignFeed.getFeedId());
             }*/


             resultItem.FeedId = feedId;
             resultItem.CampaignId = campaignId;
             //resultItem.FeedItemId = feedItemId;
             resultItem.FeedTypeId = feedTypeId;
             resultItem.HasError = false;

             items.add(resultItem);



             try {

                 JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                 Marshaller marshallerObj = contextObj.createMarshaller();
                 marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                 StringWriter sw = new StringWriter();

                 res.Items = items;

                 marshallerObj.marshal(res, sw);
                 result = sw.getBuffer().toString();
                 System.out.println(result);
                 String s = "";

             } catch (Exception exc) {
                 exc.printStackTrace();
                 result = exc.getMessage();
             }

             return result;






         }catch (Exception exc){
             GA_Result res = new GA_Result();

             ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

             GA_ResultItem error = new GA_ResultItem();

             ErrorsStruct errors = new ErrorsStruct();

             errors.Message = exc.getMessage();

             errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

             com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

             StringWriter st = new StringWriter();
             exc.printStackTrace(new PrintWriter(st));

             err.UnknownError = st.toString();

             errors.Errors.add(err);

             error.Errors = errors;

             error.HasError = true;

             items.add(error);

             String result = "";

             try {

                 JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                 Marshaller marshallerObj = contextObj.createMarshaller();
                 marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                 StringWriter sw = new StringWriter();

                 res.Items = items;

                 marshallerObj.marshal(res, sw);
                 result = sw.getBuffer().toString();
                 System.out.println(result);
                 return result;

             } catch (Exception ex) {
                 ex.printStackTrace();
                 result = ex.getMessage();
                 return result;
             }
         }



    }

    public String GetAllFeeds(){

        try{

            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();


            ArrayList<GA_ResultItem> feeds = new ArrayList<GA_ResultItem>();



            FeedServiceInterface feedService = sf.GetFeedServiceInterface(this._clientId);
            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));
            selector.setFields(new String[]{"Id", "Name", "Origin", "Attributes", "FeedStatus"});

            FeedPage page = null;


            try {

                do {

                    page = feedService.get(selector);


                    if (page.getEntries() != null) {

                        for (Feed feed : page.getEntries()) {


                            GA_ResultItem resultItem = new GA_ResultItem();

                            resultItem.FeedId = feed.getId();
                            resultItem.FeedName = feed.getName();
                            resultItem.FeedOrigin = feed.getOrigin().getValue();
                            resultItem.FeedStatus = feed.getStatus().getValue();

                            for (FeedAttribute feedAttribute : feed.getAttributes()){

                                GA_FeedAttribute attribute = new GA_FeedAttribute();

                                attribute.FeedAttrName = feedAttribute.getName();
                                attribute.FeedAttrId = feedAttribute.getId();
                                attribute.FeedAttrType = feedAttribute.getType().getValue();


                                resultItem.FeedAttributes.add(attribute);

                            }


                            //result.add(customer.getCustomerId());
                            //System.out.println("Id: " + customer.getCustomerId() + ", Name: " + customer.getName());
                            //System.out.println("ID: " +  feed.getId() + " - Name: "  + feed.getName() + " - Origin: " + feed.getOrigin());
                            feeds.add(resultItem);
                        }

                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = feeds;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            }




            return result;


        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }




    }

    public ArrayList<FeedReport> GetAllFeedsReport(String clientId){
        try{
            String result = "";
            GA_Report res = new GA_Report();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();
            //ArrayList<GA_ResultItem> feeds = new ArrayList<GA_ResultItem>();
            FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(clientId);
            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));


            selector.setFields(new String[]{"FeedId", "FeedMappingId", "PlaceholderType", "Status", "AttributeFieldMappings"});

            Predicate predicate = new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[] {"REMOVED"});
            Predicate[] predicates = new Predicate[] {predicate};
            //selector.setPredicates(predicates);

            FeedMappingPage page = null;

            ArrayList<FeedReport> feeds = new ArrayList<FeedReport>();

            try {
                do {
                    page = feedMappingService.get(selector);
                    if (page.getEntries() != null) {
                        for (FeedMapping feedMapping : page.getEntries()) {
                            FeedReport feedReport = new FeedReport();
                            feedReport.FeedId = feedMapping.getFeedId();
                            feedReport.FeedStatus = feedMapping.getStatus().getValue().substring(0, 1);
                            feedReport.FeedType = feedMapping.getPlaceholderType();
                            feedReport.FeedAttributes = new ArrayList<FeedAttributeReport>();

                            for (AttributeFieldMapping fieldMapping : feedMapping.getAttributeFieldMappings()){

                                FeedAttributeReport feedAttributeReport = new FeedAttributeReport();
                                feedAttributeReport.FieldId = fieldMapping.getFieldId();
                                feedAttributeReport.FeedAttributeId = fieldMapping.getFeedAttributeId();

                                feedReport.FeedAttributes.add(feedAttributeReport);
                            }
                            feeds.add(feedReport);
                        }
                    }
                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);
                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }

            //res.Feeds = feeds;

            //res.Items.add(resultItem);

            /*try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Report.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                //res.Items = feeds;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            }


            return result;*/

            return feeds;


        }   catch (Exception exc){

            exc.printStackTrace();
            return new ArrayList<FeedReport>();
            /*GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }*/
        }

    }


    public String GetMapping(Long feedId){

        try{

            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();


            ArrayList<GA_ResultItem> feeds = new ArrayList<GA_ResultItem>();



            FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(this._clientId);
            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedIdPredicate =
                    new Predicate("FeedId", PredicateOperator.IN, new String[]{feedId.toString()});

            selector.setPredicates(new Predicate[]{feedIdPredicate});
            selector.setFields(new String[]{"FeedId", "FeedMappingId", "PlaceholderType", "Status", "AttributeFieldMappings"});

            FeedMappingPage page = null;

            try {

                do {

                    page = feedMappingService.get(selector);

                    if (page.getEntries() != null) {

                        for (FeedMapping feedMapping : page.getEntries()) {


                            GA_ResultItem resultItem = new GA_ResultItem();

                            /*resultItem.FeedId = feed.getId();
                            resultItem.FeedName = feed.getName();
                            resultItem.FeedOrigin = feed.getOrigin().getValue();
                            resultItem.FeedStatus = feed.getStatus().getValue();

                            for (FeedAttribute feedAttribute : feed.getAttributes()){

                                GA_FeedAttribute attribute = new GA_FeedAttribute();

                                attribute.FeedAttrName = feedAttribute.getName();
                                attribute.FeedAttrId = feedAttribute.getId();
                                attribute.FeedAttrType = feedAttribute.getType().getValue();


                                resultItem.FeedAttributes.add(attribute);

                            }   */


                            //result.add(customer.getCustomerId());
                            //System.out.println("Id: " + customer.getCustomerId() + ", Name: " + customer.getName());
                            System.out.println("FeedId: " +  feedMapping.getFeedId() + " - Mapping Id: "  + feedMapping.getFeedMappingId() + " - Type: " + feedMapping.getPlaceholderType());
                            //feeds.add(resultItem);
                        }

                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }


            //res.Items.add(resultItem);

            /*try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                //res.Items = feeds;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            } */


            return result;


        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }



    }

    public String GetFeedItems(Long feedId){

        try{

            String result = "";

            GA_Result res = new GA_Result();

            // Get the instance of service's factory
            ServiceFactory sf = ServiceFactory.getInstance();

            Util util = new Util();


            FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);

            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedIdPredicate =
                    new Predicate("FeedId", PredicateOperator.IN, new String[]{feedId.toString()});

            selector.setPredicates(new Predicate[]{feedIdPredicate});
            selector.setFields(new String[]{"FeedId", "FeedItemId", "AttributeValues", "Status"});

            FeedItemPage page = null;

            GA_ResultItem resultItem = new GA_ResultItem();

            resultItem.FeedId = feedId;

            try {

                do {

                    page = feedItemService.get(selector);


                    if (page.getEntries() != null) {

                        for (FeedItem feedItem : page.getEntries()) {

                            GA_FeedItem item = new GA_FeedItem();
                            item.FeedItemStatus = feedItem.getStatus().getValue();
                            item.FeedItemId = feedItem.getFeedItemId();
                            item.FeedAttributes = new ArrayList<GA_FeedAttribute>();
                            for (FeedItemAttributeValue attValue : feedItem.getAttributeValues()){
                                GA_FeedAttribute attribute = new GA_FeedAttribute();
                                attribute.FeedAttrId = attValue.getFeedAttributeId();
                                if (attValue.getBooleanValue() != null){
                                    System.out.println("\t" + attValue.getBooleanValue());
                                    attribute.FeedItemValue = attValue.getBooleanValue().toString();

                                }else if (attValue.getDoubleValue() != null){
                                    System.out.println("\t" + attValue.getDoubleValue());
                                    attribute.FeedItemValue = attValue.getDoubleValue().toString();
                                }else if (attValue.getStringValue() != null){
                                    System.out.println("\t" + attValue.getStringValue());
                                    attribute.FeedItemValue = attValue.getStringValue().toString();
                                }else if (attValue.getIntegerValue() != null){
                                    System.out.println("\t" + attValue.getIntegerValue());
                                    attribute.FeedItemValue = attValue.getIntegerValue().toString();
                                }

                                item.FeedAttributes.add(attribute);

                            }
                            resultItem.FeedItems.add(item);

                        }



                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }


            res.Items.add(resultItem);

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                //res.Items = feeds;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            }


            return result;

        }catch (Exception exc){
            GA_Result res = new GA_Result();

            ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();

            GA_ResultItem error = new GA_ResultItem();

            ErrorsStruct errors = new ErrorsStruct();

            errors.Message = exc.getMessage();

            errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();

            com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();

            StringWriter st = new StringWriter();
            exc.printStackTrace(new PrintWriter(st));

            err.UnknownError = st.toString();

            errors.Errors.add(err);

            error.Errors = errors;

            error.HasError = true;

            items.add(error);

            String result = "";

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                res.Items = items;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                return result;

            } catch (Exception ex) {
                ex.printStackTrace();
                result = ex.getMessage();
                return result;
            }
        }


    }


    public ArrayList<GA_CallsFeedItem> GetCallsFeedItemReport(String accountId){
        SetClientId(accountId);

        ArrayList<GA_CallsFeedItem> result = new ArrayList<GA_CallsFeedItem>();
        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();

        try {
            FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(accountId);
            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedTypePredicate = new Predicate("PlaceholderType", PredicateOperator.IN, new String[]{"2"});
            Predicate statusPredicate = new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[]{"REMOVED"});

            selector.setPredicates(new Predicate[]{feedTypePredicate, statusPredicate});
            selector.setFields(new String[]{"FeedId", "FeedMappingId", "PlaceholderType", "Status", "AttributeFieldMappings"});

            FeedMappingPage page = null;

            //ArrayList<FeedReport> feeds = new ArrayList<FeedReport>();

            try {

                do {

                    page = feedMappingService.get(selector);

                    if (page.getEntries() != null) {

                        for (FeedMapping feedMapping : page.getEntries()) {

                            //if (!feedMapping.getFeedId().equals(feedMapping.getFeedMappingId())){

                            GA_CallsFeedItem feedItem = new GA_CallsFeedItem();

                            feedItem.FeedId = feedMapping.getFeedId();
                            feedItem.FeedItems = new ArrayList<CallsFeedItem>();

                            feedItem.FeedItems = GetFeedItemsCallsByFeed(feedItem.FeedId);

                            result.add(feedItem);
                            //}

                        }

                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        Finalize();
        return result;
    }


    public ArrayList<GA_SitelinksFeedItem> GetSitelinksFeedItemReport(String accountId){

        SetClientId(accountId);

        ArrayList<GA_SitelinksFeedItem> result = new ArrayList<GA_SitelinksFeedItem>();
        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();

        try {
            FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(accountId);
            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedTypePredicate = new Predicate("PlaceholderType", PredicateOperator.IN, new String[]{"1"});
            Predicate statusPredicate = new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[]{"REMOVED"});

            selector.setPredicates(new Predicate[]{feedTypePredicate, statusPredicate});
            selector.setFields(new String[]{"FeedId", "FeedMappingId", "PlaceholderType", "Status", "AttributeFieldMappings"});

            FeedMappingPage page = null;

            //ArrayList<FeedReport> feeds = new ArrayList<FeedReport>();

            try {

                do {

                    page = feedMappingService.get(selector);

                    if (page.getEntries() != null) {

                        for (FeedMapping feedMapping : page.getEntries()) {

                            //if (!feedMapping.getFeedId().equals(feedMapping.getFeedMappingId())){

                            GA_SitelinksFeedItem feedItem = new GA_SitelinksFeedItem();

                            feedItem.FeedId = feedMapping.getFeedId();
                            feedItem.FeedItems = new ArrayList<SitelinksFeedItem>();

                            feedItem.FeedItems = GetFeedItemsByFeed(feedItem.FeedId);

                            result.add(feedItem);
                            //}

                        }

                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        Finalize();
        return result;
    }

    public ArrayList<GA_LocationExtensionsFeedItem> GetLocationExtensionsFeedItemReport(String accountId){

        SetClientId(accountId);

        ArrayList<GA_LocationExtensionsFeedItem> result = new ArrayList<GA_LocationExtensionsFeedItem>();
        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();

        try {
            FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(accountId);
            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedTypePredicate = new Predicate("PlaceholderType", PredicateOperator.IN, new String[]{"7"});
            Predicate statusPredicate = new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[]{"REMOVED"});

            selector.setPredicates(new Predicate[]{feedTypePredicate, statusPredicate});
            selector.setFields(new String[]{"FeedId", "FeedMappingId", "PlaceholderType", "Status", "AttributeFieldMappings"});

            FeedMappingPage page = null;

            //ArrayList<FeedReport> feeds = new ArrayList<FeedReport>();

            try {

                do {

                    page = feedMappingService.get(selector);

                    if (page.getEntries() != null) {

                        for (FeedMapping feedMapping : page.getEntries()) {

                            //if (!feedMapping.getFeedId().equals(feedMapping.getFeedMappingId())){

                            GA_LocationExtensionsFeedItem feedItem = new GA_LocationExtensionsFeedItem();

                            feedItem.FeedId = feedMapping.getFeedId();
                            feedItem.FeedItems = new ArrayList<LocationExtensionsFeedItem>();

                            feedItem.FeedItems = GetFeedItemsLocationsByFeed(feedItem.FeedId);

                            result.add(feedItem);
                            //}

                        }

                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        Finalize();
        return result;
    }


    private ArrayList<SitelinksFeedItem> GetFeedItemsByFeed(Long feedId){
        // Get the instance of service's factory
        ArrayList<SitelinksFeedItem> result = new ArrayList<SitelinksFeedItem>();
        ServiceFactory sf = ServiceFactory.getInstance();
        try {
            FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);

            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedIdPredicate =
                    new Predicate("FeedId", PredicateOperator.IN, new String[]{feedId.toString()});
            Predicate statusPredicate = new Predicate("Status", PredicateOperator.NOT_EQUALS, new String[]{"REMOVED"});

            selector.setPredicates(new Predicate[]{feedIdPredicate, statusPredicate});
            selector.setFields(new String[]{"FeedId", "FeedItemId", "AttributeValues", "Status"});

            FeedItemPage page = null;

            try {

                do {

                    page = feedItemService.get(selector);


                    if (page.getEntries() != null) {

                        for (FeedItem feedItem : page.getEntries()) {

                            SitelinksFeedItem fi = new SitelinksFeedItem();

                            fi.FeedItemId = feedItem.getFeedItemId();
                            fi.FeedStatus = feedItem.getStatus().getValue().substring(0, 1);
                            fi.FeedAttributes = new ArrayList<GA_FeedAttribute>();

                            for (FeedItemAttributeValue attValue : feedItem.getAttributeValues()) {
                                GA_FeedAttribute attribute = new GA_FeedAttribute();
                                attribute.FeedAttrId = attValue.getFeedAttributeId();
                                if (attValue.getBooleanValue() != null) {
                                    attribute.FeedItemValue = attValue.getBooleanValue().toString();

                                } else if (attValue.getDoubleValue() != null) {
                                    attribute.FeedItemValue = attValue.getDoubleValue().toString();
                                } else if (attValue.getStringValue() != null) {
                                    attribute.FeedItemValue = attValue.getStringValue().toString();
                                } else if (attValue.getIntegerValue() != null) {
                                    attribute.FeedItemValue = attValue.getIntegerValue().toString();
                                }
                                //System.out.println(attribute.FeedItemValue);
                                fi.FeedAttributes.add(attribute);

                            }
                            result.add(fi);
                            //System.out.println(fi.FeedStatus);

                        }


                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        return result;
    }

    private ArrayList<CallsFeedItem> GetFeedItemsCallsByFeed(Long feedId){
        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();
        ArrayList<CallsFeedItem> result = new ArrayList<CallsFeedItem>();
        try {
            FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);

            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedIdPredicate =
                    new Predicate("FeedId", PredicateOperator.IN, new String[]{feedId.toString()});

            selector.setPredicates(new Predicate[]{feedIdPredicate});
            selector.setFields(new String[]{"FeedId", "FeedItemId", "AttributeValues", "Status"});

            FeedItemPage page = null;
            try {

                do {

                    page = feedItemService.get(selector);


                    if (page.getEntries() != null) {

                        for (FeedItem feedItem : page.getEntries()) {

                            CallsFeedItem fi = new CallsFeedItem();

                            fi.FeedItemId = feedItem.getFeedItemId();
                            fi.FeedStatus = feedItem.getStatus().getValue().substring(0, 1);
                            fi.FeedAttributes = new ArrayList<GA_FeedAttribute>();

                            for (FeedItemAttributeValue attValue : feedItem.getAttributeValues()) {
                                GA_FeedAttribute attribute = new GA_FeedAttribute();
                                attribute.FeedAttrId = attValue.getFeedAttributeId();
                                if (attValue.getBooleanValue() != null) {
                                    attribute.FeedItemValue = attValue.getBooleanValue().toString();
                                } else if (attValue.getDoubleValue() != null) {
                                    attribute.FeedItemValue = attValue.getDoubleValue().toString();
                                } else if (attValue.getStringValue() != null) {
                                    attribute.FeedItemValue = attValue.getStringValue().toString();
                                } else if (attValue.getIntegerValue() != null) {
                                    attribute.FeedItemValue = attValue.getIntegerValue().toString();
                                }

                                fi.FeedAttributes.add(attribute);

                            }
                            result.add(fi);

                        }


                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        return result;
    }

    private ArrayList<LocationExtensionsFeedItem> GetFeedItemsLocationsByFeed(Long feedId){
        ArrayList<LocationExtensionsFeedItem> result = new ArrayList<LocationExtensionsFeedItem>();
        // Get the instance of service's factory
        ServiceFactory sf = ServiceFactory.getInstance();
        try {
            FeedItemServiceInterface feedItemService = sf.GetFeedItemServiceInterface(this._clientId);

            int offset = 0;
            Selector selector = new Selector();

            selector.setPaging(new Paging(offset, PAGE_SIZE));

            Predicate feedIdPredicate =
                    new Predicate("FeedId", PredicateOperator.IN, new String[]{feedId.toString()});

            selector.setPredicates(new Predicate[]{feedIdPredicate});
            selector.setFields(new String[]{"FeedId", "FeedItemId", "AttributeValues", "Status"});

            FeedItemPage page = null;
            try {

                do {

                    page = feedItemService.get(selector);


                    if (page.getEntries() != null) {

                        for (FeedItem feedItem : page.getEntries()) {

                            LocationExtensionsFeedItem fi = new LocationExtensionsFeedItem();

                            fi.FeedItemId = feedItem.getFeedItemId();
                            fi.FeedStatus = feedItem.getStatus().getValue().substring(0, 1);
                            fi.FeedAttributes = new ArrayList<GA_FeedAttribute>();

                            for (FeedItemAttributeValue attValue : feedItem.getAttributeValues()) {
                                GA_FeedAttribute attribute = new GA_FeedAttribute();
                                attribute.FeedAttrId = attValue.getFeedAttributeId();
                                if (attValue.getBooleanValue() != null) {
                                    attribute.FeedItemValue = attValue.getBooleanValue().toString();
                                } else if (attValue.getDoubleValue() != null) {
                                    attribute.FeedItemValue = attValue.getDoubleValue().toString();
                                } else if (attValue.getStringValue() != null) {
                                    attribute.FeedItemValue = attValue.getStringValue().toString();
                                } else if (attValue.getIntegerValue() != null) {
                                    attribute.FeedItemValue = attValue.getIntegerValue().toString();
                                }

                                fi.FeedAttributes.add(attribute);

                            }
                            result.add(fi);

                        }


                    }

                    offset += PAGE_SIZE;
                    selector.getPaging().setStartIndex(offset);

                } while (offset < page.getTotalNumEntries());


            } catch (RemoteException e) {
                e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
            }
        } catch (Exception ex) {
            ex.printStackTrace(System.out);
        }

        return result;

    }

    public String GetFeedsByType(Integer feedType){
          try{
              String result = "";
              GA_Report res = new GA_Report();
              // Get the instance of service's factory
              ServiceFactory sf = ServiceFactory.getInstance();
              //ArrayList<GA_ResultItem> feeds = new ArrayList<GA_ResultItem>();
              FeedMappingServiceInterface feedMappingService = sf.GetFeedMappingServiceInterface(this._clientId);
              int offset = 0;
              Selector selector = new Selector();
              selector.setPaging(new Paging(offset, PAGE_SIZE));
              Predicate feedTypePredicate =
                      new Predicate("PlaceholderType", PredicateOperator.IN, new String[]{feedType.toString()});
              selector.setPredicates(new Predicate[]{feedTypePredicate});
              selector.setFields(new String[]{"FeedId", "FeedMappingId", "PlaceholderType", "Status", "AttributeFieldMappings"});
              FeedMappingPage page = null;
              ArrayList<FeedReport> feeds = new ArrayList<FeedReport>();
              try {
                  do {
                      page = feedMappingService.get(selector);
                      if (page.getEntries() != null) {
                          for (FeedMapping feedMapping : page.getEntries()) {
                              FeedReport feedReport = new FeedReport();
                              feedReport.FeedId = feedMapping.getFeedId();
                              feedReport.FeedStatus = feedMapping.getStatus().getValue();
                              feedReport.FeedType = feedMapping.getPlaceholderType();
                              feedReport.FeedAttributes = new ArrayList<FeedAttributeReport>();
                              for (AttributeFieldMapping fieldMapping : feedMapping.getAttributeFieldMappings()){
                                  FeedAttributeReport feedAttributeReport = new FeedAttributeReport();
                                  feedAttributeReport.FieldId = fieldMapping.getFieldId();
                                  feedAttributeReport.FeedAttributeId = fieldMapping.getFeedAttributeId();
                                  feedReport.FeedAttributes.add(feedAttributeReport);
                              }
                              feeds.add(feedReport);
                          }
                      }
                      offset += PAGE_SIZE;
                      selector.getPaging().setStartIndex(offset);
                  } while (offset < page.getTotalNumEntries());
              } catch (RemoteException e) {
                  e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
              }
              res.Feeds = feeds;

              //res.Items.add(resultItem);

            try {

                JAXBContext contextObj = JAXBContext.newInstance(GA_Report.class);

                Marshaller marshallerObj = contextObj.createMarshaller();
                marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);

                StringWriter sw = new StringWriter();

                //res.Items = feeds;

                marshallerObj.marshal(res, sw);
                result = sw.getBuffer().toString();
                System.out.println(result);
                String s = "";

            } catch (Exception exc) {
                exc.printStackTrace();
                result = exc.getMessage();
            }
              return result;

          }   catch (Exception exc){
              GA_Result res = new GA_Result();
              ArrayList<GA_ResultItem> items = new ArrayList<GA_ResultItem>();
              GA_ResultItem error = new GA_ResultItem();
              ErrorsStruct errors = new ErrorsStruct();
              errors.Message = exc.getMessage();
              errors.Errors = new ArrayList<com.genexususa.eo.google.data.Error>();
              com.genexususa.eo.google.data.Error err = new com.genexususa.eo.google.data.Error();
              StringWriter st = new StringWriter();
              exc.printStackTrace(new PrintWriter(st));
              err.UnknownError = st.toString();
              errors.Errors.add(err);
              error.Errors = errors;
              error.HasError = true;
              items.add(error);
              String result = "";

              try {
                  JAXBContext contextObj = JAXBContext.newInstance(GA_Result.class);
                  Marshaller marshallerObj = contextObj.createMarshaller();
                  marshallerObj.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
                  StringWriter sw = new StringWriter();
                  res.Items = items;
                  marshallerObj.marshal(res, sw);
                  result = sw.getBuffer().toString();
                  System.out.println(result);
                  return result;

              } catch (Exception ex) {
                  ex.printStackTrace();
                  result = ex.getMessage();
                  return result;
              }
          }
    }


}


